package io.github.biezhi.elves.selenium;

import java.io.File;
import java.util.List;
//import com.dama2.Dama2Web;
import org.openqa.selenium.By;
import java.awt.image.BufferedImage;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import io.github.biezhi.elves.utils.StringUtils;
import io.github.biezhi.elves.utils.WebDriverUtils;
import io.github.biezhi.elves.common.Constants;
import org.openqa.selenium.interactions.Actions;
import io.github.biezhi.elves.common.CookieConstants;
import io.github.biezhi.elves.utils.CreateElementScreenshot;
import io.github.biezhi.elves.utils.FileUtil;

/**
 * 企查查自动化模拟浏览器操作
 *
 */
public class QccSelenium {
	static WebDriver driver;
	
	/**
	 * 自动化模拟登陆企查查网站,获取登陆后cookie信息
	 * @param reqUrl
	 */
	private static String getLoginQccForCookie(String reqUrl) {
		String url = reqUrl;
		boolean isNullUrl = true;
		
		System.out.println("class io.github.biezhi.elves.selenium.QccSelenium，访问地址{{}}==>" + url);
		if(url.contains("cms_guquanmap") && url.indexOf("/")==0){
			url = "http://www.qichacha.com/index_verify?type=companysearch&back=" + reqUrl;
		}
		
		// 1、开启个浏览器并且输入链接
		try{
			boolean isKillChrome = false;
			//检测程序
			if(!StringUtils.findProcess(Constants.CHROME_PROCESS_NAME) && StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME)){
				//检测并杀掉程序
				StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME);
				isKillChrome = true;
			}
			
			if(!isKillChrome) {
				//如果没有发现chrome浏览器进程以及chromedriver驱动，则重置isKillChrome标识为true
				if(!StringUtils.findProcess(Constants.CHROME_PROCESS_NAME) && !StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME)){
					isKillChrome = true;
				}
			}
			
			if(driver==null || isKillChrome){
				WebDriver driver1 = WebDriverUtils.getChromeDriver(url);
				driver = driver1;
			}else{
				driver.get(url);
//				driver.navigate().refresh();
			}
			
			if(!isNullUrl){
				List<WebElement> errorElement = driver.findElements(By.cssSelector(".message"));
				if(errorElement!=null && errorElement.size()>0){
					String errorText = errorElement.get(0).getText();
					if(errorText.equals(Constants.QCC_ERROR_CONTENT)){
						driver.quit();
						String requestUrl = url.replace("http://www.qichacha.com/", "http://www.qichacha.com/index_verify?type=companysearch&back=/");
						driver = WebDriverUtils.getChromeDriver(requestUrl);
					}
				}
				
				// 点击频繁页面【登录】按钮
				List<WebElement> loginElements = driver.findElements(By.cssSelector("a[href=\"/user_login\"]"));
				if(loginElements!=null && loginElements.size()>0){
					WebElement loginElement = driver.findElement(By.cssSelector("a[href=\"/user_login\"]"));
					WebDriverUtils.scrollToElementAndClick(loginElement, driver);
				}
			}
			
			// 2、向企查查登录框输入框输入用户名和密码
			List<WebElement> nameNormalElements = driver.findElements(By.id("nameNormal"));
			if(nameNormalElements!=null && nameNormalElements.size()>0){
				WebDriverUtils.inputStrByJS(driver, "nameNormal", "13710729639");
				WebDriverUtils.inputStrByJS(driver, "pwdNormal", "290990www");
			}
	
			// 休息3秒，加载数据
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			Actions action = new Actions(driver);
			
			//处理滑动滑块最右边以及点击图片文字操作
			moveSliderAndClickImgFont(driver, action);
			
			//点击【会员登录】按钮
			List<WebElement> submitLoginElements = driver.findElements(By.xpath("//*[@id=\"user_login_normal\"]/button/strong"));
			if(submitLoginElements!=null && submitLoginElements.size()>0){
				System.out.println("点击【会员登录】按钮......");
				WebElement submitLoginElement = driver.findElement(By.xpath("//*[@id=\"user_login_normal\"]/button/strong"));
				WebDriverUtils.scrollToElementAndClick(submitLoginElement, driver);
			}
			
			// 休息1秒，加载数据
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			//点击【验证一下】按钮
			List<WebElement> verifyElements = driver.findElements(By.id("verify"));
			if(verifyElements!=null && verifyElements.size()>0){
				//处理滑动滑块最右边以及点击图片文字操作
//				moveSliderAndClickImgFont(driver, action);
				
				WebElement verifyElement = driver.findElement(By.id("verify"));
				verifyElement.click();
			}
						
			//向浏览器添加cookie信息
			System.out.println("获取浏览器cookie信息......");
			String qccCookie = WebDriverUtils.getBrowserCookies(driver);
//			driver.quit();
			return qccCookie;
		}catch(Exception e){
			//检测并杀掉程序
			StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME);
			
			System.out.println("io.github.biezhi.elves.selenium.QccSelenium类getLoginQccForCookie方法，获取企查查cookie信息异常{{}}==>" + StringUtils.getErrorInfoFromException(e));
			System.out.println("休眠5000毫秒......");
			try{
				Thread.sleep(5000);
			}catch(Exception e1){}
			
			System.out.println("休眠5000毫秒后，再次调用自动化模拟登陆企查查网站,获取登陆后cookie信息方法");
			getLoginQccForCookie(url);
		}
		return "";
	}
	
	/**
	 * 拖动滑块最右边
	 * @param driver
	 * @param action
	 */
	private static void moveSliderToRight(WebDriver driver,Actions action){
		int offset = 10;
		int maxOffset = 80;
		List<WebElement> draggers = driver.findElements(By.xpath("//*[@id=\"nc_1_n1z\"]"));
		if(draggers!=null && draggers.size()>0){
			WebElement dragger = driver.findElement(By.xpath("//*[@id=\"nc_1_n1z\"]"));
			action.clickAndHold(dragger).build().perform();
			
			for(int i=10;i<=maxOffset;i=i+10){
				try {
					int moveOffset = offset + i;
					Thread.sleep(2000);
					action.moveByOffset(moveOffset, 0).perform();
					if(moveOffset>=maxOffset){
						break;
					}
				} catch (Exception e) {
					System.out.println("执行滑块异常,异常信息如下{{}}==>" + StringUtils.getErrorInfoFromException(e));
				}
			}
		}
	}
	
	/**
	 * 处理滑动滑块最右边以及点击图片文字操作
	 * @param driver
	 * @param action
	 */
	private static void moveSliderAndClickImgFont(WebDriver driver,Actions action){
		//执行滑块操作,拖动滑块最右边
		moveSliderToRight(driver,action);
		
		// 休息3秒，加载数据
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 释放鼠标
		action.release();
		
		//点击滑块处【刷新】按钮
		clickReloadSlider(driver,action);

		List<WebElement> contentCodeElements = driver.findElements(By.id("nc_1__scale_text"));
		if(contentCodeElements!=null && contentCodeElements.size()>0){
			WebElement contentCodeElement = driver.findElement(By.id("nc_1__scale_text"));
			String contentCodeText = contentCodeElement.getText();
			contentCodeText = contentCodeText.replace("请点击图中的“", "").replace("”字", "");
			
			List<WebElement> imgElements = driver.findElements(By.cssSelector(".clickCaptcha_img > img"));
			if(imgElements!=null && imgElements.size()>0){
				WebElement imgElement = driver.findElement(By.cssSelector(".clickCaptcha_img > img"));
				try {
					String filePathOne = "f:/scale_text.png";
					String filePathTwo = "f:/clickCaptcha.png";
					String mergeImgFilePath = "f:/hebing.png";
					FileUtils.copyFile(CreateElementScreenshot.captureElement(imgElement), new File(filePathTwo));
					BufferedImage scaleTextImg = CreateElementScreenshot.getImageWidthAndHeight(filePathTwo);
					FileUtils.copyFile(CreateElementScreenshot.captureElement(contentCodeElement,scaleTextImg.getWidth()), new File(filePathOne));
					
					//两张图合并成一张图(两张图的宽度必须一致)
					CreateElementScreenshot.mergeImage(filePathOne, filePathTwo, mergeImgFilePath);
					
					// 休息2秒，加载数据
//					try {
//						Thread.sleep(2000);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
					
					System.out.println("开始识别图中文字位置坐标......");
//					String pointXY = Dama2Web.getDama2ImgPoint(mergeImgFilePath,Constants.IS_PROXY);
					String pointXY ="";
					if(!StringUtils.isNullOrEmpty(pointXY)){
						String[] pointXYs = pointXY.split(",");
						int x = Integer.parseInt(pointXYs[0].trim());
						int y = Integer.parseInt(pointXYs[1].trim());
						action.moveToElement(imgElement, x+2, y-34).click().perform();
					}
					System.out.println("识别图中文字位置坐标完成,坐标为{{}}==>" + pointXY);
				} catch (Exception e) {
					System.out.println("识别图中文字调用接口异常,异常信息如下{{}}==>" + StringUtils.getErrorInfoFromException(e));
				}
			}
		}
	}
	
	/**
	 * 点击滑块处【刷新】按钮
	 * @param driver
	 * @param action
	 */
	private static void clickReloadSlider(WebDriver driver,Actions action){
		List<WebElement> reloadDivElements = driver.findElements(By.cssSelector(".errloading"));
		if(reloadDivElements!=null && reloadDivElements.size()>0){
			WebElement err = driver.findElement(By.xpath("//*[@id=\"dom_id_one\"]/div/span/a"));
			err.click();
			
			// 休息2秒，加载数据
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			//再次执行滑块操作,拖动滑块最右边
			moveSliderToRight(driver,action);
		}
	}
	
	/**
	 * 重置企查查cookie信息
	 * 
	 * @param url
	 * @return
	 */
	public static String reloadQccCookie(String url){
		if(!"0".equals(Constants.QCC_PAQU_STATE)){
//			System.out.println("访问过于频繁，需手动拖动企查查滑块最右边。。。。。。");
//			Constants.QCC_PAQU_STATE = "0";
			
			System.out.println("访问过于频繁，selenium启动chrome浏览器自动拖动企查查滑块最右边。。。。。。");
			//根据爬取状态返回登录操作cookie信息
			String cookieValue = getQccCookie(url, Constants.QCC_PAQU_STATE);
			if(!StringUtils.isNullOrEmpty(cookieValue)){
				CookieConstants.QYY_CCA_COOKIE = cookieValue;
				Constants.QCC_PAQU_STATE = "0";
				System.out.println("io.github.biezhi.elves.selenium.QccSelenium类下的reloadQccCookie方法{{}}==>" + cookieValue);
				return CookieConstants.QYY_CCA_COOKIE;
			}
			
//			System.out.println("访问过于频繁，重置代理ip后，再次访问企查查。。。。。。");
//			Map<String,Object> proxyIpMap = StringUtils.getHttpProxyIp(0);
//			if(proxyIpMap!=null && proxyIpMap.size()>0){
//				if(proxyIpMap.containsKey("proxyHost")){
//					Constants.PROXY_IP = StringUtils.getValueForKey("proxyHost", proxyIpMap);
//				}
//				if(proxyIpMap.containsKey("proxyHost")){
//					Constants.PROXY_PORT = StringUtils.getIntValueForKey("proxyPort", proxyIpMap);
//				}
//			}
		}
		return CookieConstants.QYY_CCA_COOKIE;
	}
	
	/**
	 * 根据爬取状态返回登录操作cookie信息
	 * @param url
	 * @param state
	 * @return
	 */
	private static String getQccCookie(String url,String state){
		String cookieValue = "";
		switch(state){
			case "1":
				cookieValue = getLoginQccForCookie(url);
				break;
			case "2":
				cookieValue = getLoginQccForCookie(url);
		}
		return cookieValue;
	}
	
	/**
	 * 自动化模拟登陆采标网网站
	 * http://www.bidcenter.com.cn/
	 * @param reqUrl
	 */
	private static String getLoginCbw(String reqUrl) {
		String url = reqUrl;
		boolean isNullUrl = true;
		
		// 1、开启个浏览器并且输入链接
		try{
			boolean isKillChrome = false;
			//检测程序
			if(!StringUtils.findProcess(Constants.CHROME_PROCESS_NAME) && StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME)){
				//检测并杀掉程序
				StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME);
				isKillChrome = true;
			}
			
			if(!isKillChrome) {
				//如果没有发现chrome浏览器进程以及chromedriver驱动，则重置isKillChrome标识为true
				if(!StringUtils.findProcess(Constants.CHROME_PROCESS_NAME) && !StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME)){
					isKillChrome = true;
				}
			}
			
			if(driver==null || isKillChrome){
				WebDriver driver1 = WebDriverUtils.getChromeDriver(url);
				driver = driver1;
			}else{
				driver.get(url);
//				driver.navigate().refresh();
			}
			
			List<WebElement> myDivElements = driver.findElements(By.id("myDiv"));
			if (myDivElements != null && myDivElements.size() > 0) {
				String result = driver.findElement(By.xpath("/html")).getAttribute("innerHTML");
				FileUtil.createFile("test", result, "html");
			}
			
			// 点击频繁页面【登录】按钮
			List<WebElement> loginElements = driver.findElements(By.cssSelector("a[href=\"/user_login\"]"));
			if(loginElements!=null && loginElements.size()>0){
				WebElement loginElement = driver.findElement(By.cssSelector("a[href=\"/user_login\"]"));
				WebDriverUtils.scrollToElementAndClick(loginElement, driver);
			}
			
			// 2、向企查查登录框输入框输入用户名和密码
			List<WebElement> nameNormalElements = driver.findElements(By.id("nameNormal"));
			if(nameNormalElements!=null && nameNormalElements.size()>0){
				WebDriverUtils.inputStrByJS(driver, "nameNormal", "13660447695");
				WebDriverUtils.inputStrByJS(driver, "pwdNormal", "123456");
			}
	
			// 休息3秒，加载数据
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			Actions action = new Actions(driver);
			
			//处理滑动滑块最右边以及点击图片文字操作
			moveSliderAndClickImgFont(driver, action);
			
			//点击【会员登录】按钮
			List<WebElement> submitLoginElements = driver.findElements(By.xpath("//*[@id=\"user_login_normal\"]/button/strong"));
			if(submitLoginElements!=null && submitLoginElements.size()>0){
				System.out.println("点击【会员登录】按钮......");
				WebElement submitLoginElement = driver.findElement(By.xpath("//*[@id=\"user_login_normal\"]/button/strong"));
				WebDriverUtils.scrollToElementAndClick(submitLoginElement, driver);
			}
			
			// 休息1秒，加载数据
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			//向浏览器添加cookie信息
			System.out.println("获取浏览器cookie信息......");
			String qccCookie = WebDriverUtils.getBrowserCookies(driver);
//			driver.quit();
			return qccCookie;
		}catch(Exception e){
			//检测并杀掉程序
			StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME);
			
			System.out.println("io.github.biezhi.elves.selenium.QccSelenium类getLoginQccForCookie方法，获取企查查cookie信息异常{{}}==>" + StringUtils.getErrorInfoFromException(e));
			System.out.println("休眠5000毫秒......");
			try{
				Thread.sleep(5000);
			}catch(Exception e1){}
			
			System.out.println("休眠5000毫秒后，再次调用自动化模拟登陆企查查网站,获取登陆后cookie信息方法");
			getLoginCbw(url);
		}
		return "";
	}
	
	public static void main(String[] args) {
		getLoginCbw("http://www.bidcenter.com.cn/news-47372076-4.html");
	}
}